package org.example.controller;


import lombok.RequiredArgsConstructor;

import org.example.entity.AjaxResult;
import org.example.entity.Token;
import org.example.entity.vo.LoginVo;
import org.example.security.UserDetailServiceImpl;
import org.example.security.UserDetailsImpl;
import org.example.service.TokenService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
public class LoginController {


    private final TokenService tokenService;

    private final AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVo loginVo) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getLoginName(), loginVo.getPassword());
        //调用登录
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        Token token = tokenService.createToken((UserDetailsImpl) authenticate.getPrincipal());
        return AjaxResult.ok(token);
    }

    @GetMapping("/logout")
    public AjaxResult logout(@RequestHeader String token) {
        tokenService.removeToken(token);
        return AjaxResult.ok();
    }
}
